<template>
    <div class="table">
        <div class="container">
            <div class="handle-box">
                <el-input v-model="params.name" size="mini" placeholder="请输入歌手名"
                          style="width: 160px;"></el-input>
                <el-button type="primary" size="mini" @click="getList">查询</el-button>
                <el-button type="primary" size="mini" @click="centerDialogVisible=true">添加歌手</el-button>
                <el-button type="danger" size="mini" @click="deleteHandle()">批量删除</el-button>
            </div>
        </div>
        <el-table size="mini" border width="100px"
                  :data="dataList" @selection-change="selectionChangeHandle">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column label="歌手图片" width="110" align="center">
                <template slot-scope="scope">
                    <div class="singer-img">
                        <img :src="getUrl(scope.row.pic)"
                             style="width: 100%" alt="歌手图片">
                        <el-upload :action="uploadUrl(scope.row.id)"
                                   :before-upload="handleAvatarUpload"
                                   :on-success="handleAvatarSuccess"
                                   :show-file-list="false">
                            <el-button size="mini">更新图片</el-button>
                        </el-upload>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="歌手" width="120px" align="center"></el-table-column>
            <el-table-column prop="sex" label="性别" width="50px" align="center">
                <template slot-scope="scope">
                    {{changeSex(scope.row.sex)}}
                </template>
            </el-table-column>
            <el-table-column type="date" prop="birth" label="出生日期" width="120px" align="center">
                <template slot-scope="scope">
                    {{attachBirth(scope.row.birth)}}
                </template>
            </el-table-column>
            <el-table-column prop="location" label="地区" width="120px" align="center"></el-table-column>
            <el-table-column prop="introduction" label="简介">
                <template slot-scope="scope">
                    <p class="introduction">
                        {{scope.row.introduction}}</p>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250px" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" @click="editHandle(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="deleteHandle(scope.row.id)">删除</el-button>
                    <el-button size="mini" @click="songEdit(scope.row.id,scope.row.name)">歌曲管理</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="params.currPage"
                :page-sizes="[5, 10, 50, 100]"
                :page-size="params.pageSize"
                :total="params.totalCount"
                layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
        <el-dialog title="添加歌手" :visible="centerDialogVisible" center width="400px"
                   @close="closeDialog">
            <el-form :model="registerForm" ref="registerFormRef" label-width="80px">
                <el-form-item prop="name" label="歌手名" size="mini">
                    <el-input v-model="registerForm.name" placeholder="歌手名"></el-input>
                </el-form-item>
                <el-form-item label="性别" size="mini">
                    <el-radio-group v-model="registerForm.sex">
                        <el-radio :label="0">女</el-radio>
                        <el-radio :label="1">男</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="birth" label="生日" size="mini">
                    <el-date-picker type="date" placeholder="选择日期" v-model="registerForm.birth"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    style="width: 100%"></el-date-picker>
                </el-form-item>
                <el-form-item prop="location" label="地区" size="mini">
                    <el-input v-model="registerForm.location" placeholder="地区"></el-input>
                </el-form-item>
                <el-form-item prop="introduction" label="简介" size="mini">
                    <el-input v-model="registerForm.introduction" placeholder="简介" type="textarea"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button size="mini" @click="closeDialog">取消</el-button>
                <el-button size="mini" @click="saveOrUpdateSinger">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {deleteSinger, getSingerInfo, getSingerList, saveOrUpdateSinger} from '../api/index'
    import {mixin} from '../mixins/index'

    export default {
        mixins: [mixin],
        data() {
            return {
                centerDialogVisible: false,
                registerForm: {
                    id: '',
                    name: '',
                    sex: '',
                    birth: '',
                    location: '',
                    introduction: ''
                },
                dataList: [],
                tempList: [],
                params: {
                    currPage: 1,     //当前页
                    pageSize: 5,   //每页大小
                    totalCount: 1,//总记录数
                    name: '',    //查询条件
                    isPage: true //开启分页
                },
                dataListSelections: [],
            }
        },
        watch: {
            //搜索框里面的内容发生变化的时候，搜索结果table列表的内容跟着它的内容发生变化
            //页面搜索 分页后需要使用服务器搜索
            select_word: function () {
                //不采用该方法
                if (this.params.name === '') {
                    this.dataList = this.tempList
                } else {
                    this.dataList = []
                    for (let item of this.tempList) {
                        if (item.name.includes(this.params.name)) {
                            this.dataList.push(item)
                        }
                    }
                }
            }
        },
        methods: {
            getList() {
                let params = {
                    'isPage': this.params.isPage,
                    'name': this.params.name,
                    'page': this.params.currPage,
                    'limit': this.params.pageSize,
                }
                getSingerList(params).then(({data: res}) => {
                    this.dataList = res.data.list
                    // this.tempList = res.data.
                    this.params.totalCount = res.data.totalCount
                })
            },
            closeDialog() {
                this.centerDialogVisible = false
                this.$refs.registerFormRef.resetFields()
            },
            saveOrUpdateSinger() {
                //直接使用  value-format="yyyy-MM-dd"格式化
                // let d = this.registerForm.birth
                // let datetime = d.getFullYear() + '--' + d.getMonth() + '--' + d.getDate()
                // console.log(datetime)
                // console.log(this.registerForm)
                saveOrUpdateSinger(this.registerForm).then(({data: res}) => {
                    if (res.code === 0) {
                        this.notify('成功', 'success')
                        this.closeDialog()
                        this.getList()
                    } else
                        this.notify('失败', 'error')
                })
            },
            uploadUrl(id) {
                //从Vuex中获取图片上传的服务器ip
                return `${this.$store.state.HOST}/song/updateSongPic?id=${id}`
            },
            handleAvatarSuccess(res, file) {
                if (res.code === 0) {
                    this.getList()
                    this.notify('上传成功', 'success')
                } else {
                    this.notify('上传失败', 'error')
                }
            },
            handleAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
                if (!isJPG) {
                    this.$message.error('上次头像图片只能是jpg或png格式')
                    return false
                }
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!')
                    return false
                }
                return isJPG && isLt2M
            },
            editHandle(id) {
                getSingerInfo(id).then(({data: res}) => {
                        if (res.code === 0) {
                            this.registerForm = res.info
                            this.centerDialogVisible = true
                        } else {
                            this.$message.error('请稍后重试')
                        }
                    }
                )
            },
            deleteHandle(id) {
                console.log(id)
                let ids = id ? [id] : this.dataListSelections.map(item => {
                    return item.id
                })
                this.$confirm(`确定对进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const {data: res} = await deleteSinger(ids)
                    if (res.code === 0) {
                        this.getList()
                        this.$message.success('删除成功')
                    } else {
                        return this.$message.error('删除失败')
                    }
                }).catch(() => {
                    this.$message.warning('取消删除')
                })

            },
            // 多选
            selectionChangeHandle(val) {
                this.dataListSelections = val
            },
            sizeChangeHandle(val) {
                this.params.pageSize = val
                this.params.currPage = 1
                this.getList()
            },
            currentChangeHandle(val) {
                this.params.currPage = val
                this.getList()
            },
            songEdit(id, name) {
                this.$router.push({path: '/Song', query: {id, name}})
            }
        },
        created() {
            this.getList()
        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .singer-img {
        width: 100%;
        height: 100%;
        border-radius: 5px;
        margin-bottom: 5px;
        overflow: hidden;
    }

    .introduction {
        height: 100px;
        overflow-y: scroll;
        overflow-x: hidden;
    }

    /*隐藏滚动条*/
    .introduction::-webkit-scrollbar {
        display: none;
    }
</style>